<?php
if(! defined('OT_ROOT')) {
	exit('Access Denied');
}



class MakeDiy{
	public static $htmlId = 0;
	public static $htmlName = '';

	// 判断读取页面缓存内容
	public static function Start($htmlId=0){
		global $DB;

		$id		= intval(@$_POST['id']);
		$rnd	= trim(''. @$_POST['rnd']);
		$mode	= trim(''. @$_GET['mode']);

		if ($htmlId == 0){ $htmlId = $id; }
		if ($htmlId > 0){
			$htmlexe = $DB->query('select * from '. OT_dbPref .'makeDiy where MD_ID='. $htmlId);
			if (! $hr = $htmlexe->fetch()){
				self::HtmlErr('搜索不到相关记录');
			}
			if ($hr['MD_state'] == 1 && $mode != 'no'){
				if ($id == 0 || strlen($rnd) == 0){
					if (strpos(''. $hr['MD_event'],'|301|') === false){
						return ;
					}
					header('Location: '. $hr['MD_htmlName'], true, 301);
				}
				if ($hr['MD_rnd'] != $rnd){
					self::HtmlErr('校验码不对');
				}
				self::$htmlId = $htmlId;
				self::$htmlName = $hr['MD_htmlName'];
			}
			unset($hr,$htmlexe);
		
		}
	}

	public static function HtmlErr($str){
		die('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><body style="padding:0;margin:0;">'. $str .'</body></html>');
	}


	// 判断读取页面缓存内容
	public static function End($cacheData,$cacheMode='pc'){
		global $DB;

		if ($cacheMode == 'wap'){ $fieldName = 'MD_pathWap'; $dir = 'wap/'; }else{ $fieldName = 'MD_path'; $dir = ''; $cacheMode = 'pc'; }
		$webArr = array();
		$webArr = $DB->GetAll('select '. $fieldName .',MD_htmlName from '. OT_dbPref .'makeDiy where MD_state=1');

		if ($fieldName == 'MD_pathWap'){
			if (! function_exists('newfuncMDwap')){
				function newfuncMDwap($a,$b){
					return strlen($a['MD_pathWap']) < strlen($b['MD_pathWap']) ? 1 : -1;
				}
			}
			usort($webArr, 'newfuncMDwap');
		}else{
			if (! function_exists('newfuncMD')){
				function newfuncMD($a,$b){
					return strlen($a['MD_path']) < strlen($b['MD_path']) ? 1 : -1;
				}
			}
			usort($webArr, 'newfuncMD');
		}
		// print_r($webArr);die();
		foreach ($webArr as $item) {
			$cacheData = str_replace($item[$fieldName], $item['MD_htmlName'], $cacheData);
		}

		if (strlen(self::$htmlName)>0){
			if (! File::Write(OT_ROOT . $dir . self::$htmlName, $cacheData . PHP_EOL .'<!-- Html For '. TimeDate::Get() .' -->')){
				self::HtmlErr('<div style="font-size:14px;color:red;">'. $cacheMode .'生成失败!</div>');
			}else{
				if (self::$htmlId > 0){ $DB->UpdateParam('makeDiy', array('MD_htmlTime'=>TimeDate::Get()), 'MD_ID='. self::$htmlId); }
				self::HtmlErr('<div style="font-size:14px;color:green;">'. $cacheMode .'生成成功!</div>');
			}

		}
	}

}
?>